package tools

import "github.com/pkg/errors"

// PasswordCheck 校验密码。密码强度要求：8-20位，必须包含大写字母、小写字母、数字、特殊字符!@
func PasswordCheck(passwd string) error {
	indNum := [4]int{0, 0, 0, 0}
	//spCode := []byte{'!', '@', '#', '$', '%', '^', '&', '*', '_', '-'}
	spCode := []byte{'!', '@'}

	if len(passwd) < 8 {
		return errors.New("password too short")
	}

	if len(passwd) > 20 {
		return errors.New("password too long")
	}

	passwdByte := []byte(passwd)

	for _, i := range passwdByte {

		if i >= 'A' && i <= 'Z' {
			indNum[0] = 1
			continue
		}

		if i >= 'a' && i <= 'z' {
			indNum[1] = 1
			continue
		}

		if i >= '0' && i <= '9' {
			indNum[2] = 1
			continue
		}

		notEnd := 0
		for _, s := range spCode {
			if i == s {
				indNum[3] = 1
				notEnd = 1
				break
			}
		}

		if notEnd != 1 {
			return errors.New("Unsupport code")
		}

	}

	codeCount := 0

	for _, i := range indNum {
		codeCount += i
	}

	if codeCount != 4 {
		return errors.New("Too simple password")
	}

	return nil
}
